package com.study.example.login_regist;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
* @Name: UserDaoImpl
* @Description: 用户信息操作Dao实现类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-16 下午4:27:29 
* @Version: V1.0
 */
public class UserDaoImpl implements UserDao{
	
	private static File file = new File("user.txt") ;
	
	static {
		try {
			file.createNewFile() ;
		} catch (IOException e) {
			System.out.println("用户登录信息文件创建失败！");
		}
	}

	/**
	* @Name: isLogin
	* @Description: 判断用户是否登录，实现方法
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-1-16 下午4:23:49
	* @Parameters: @param username
	* @Parameters: @param password
	* @Parameters: @return
	* @Return: boolean
	 */
	@Override
	public boolean isLogin(String username, String password) {
		boolean flag = false ;
		BufferedReader reader = null ;
		try {
			//获取用户登录信息文件File对象
			reader = new BufferedReader(new FileReader(file)) ;
			String line = null ;
			//遍历已登录的用户，判断当前用户是否登录
			while((line = reader.readLine()) != null) {
				String[] datas = line.split("=") ;
				String uname = datas[0] ;
				String pwd = datas[1] ;
				if(username.equals(uname) && password.equals(pwd)) {
					flag = true ;
					break ;
				}
 			}
		} catch (FileNotFoundException e) {
			System.out.println("找不到用户登录信息文件");
		} catch (IOException e) {
			System.out.println("用户登录失败！");
		} finally {
			if(reader != null) {
				try {
					reader.close() ;
				} catch (IOException e) {
					System.out.println("用户登录释放资源失败！");
				}
			}
		}
		return flag;
	}
	
	/**
	* @Name: regist
	* @Description: 用户注册，实现方法
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-1-16 下午4:24:07
	* @Parameters: @param user 用户对象
	* @Return: void 无
	 */
	@Override
	public void regist(User user) {
		BufferedWriter writer = null ;
		try {
			//为了保证用户注册信息的追加特性，创建File对象时，构造方法必须加true。
			writer = new BufferedWriter(new FileWriter(file, true)) ;
			//拼接用户名和密码
			String u = user.getUsername() + "=" + user.getPassword() ;
			writer.write(u) ;
			writer.newLine() ;
			writer.flush() ;
		} catch (IOException e) {
			System.out.println("用户注册失败!");
		} finally {
			if(writer != null) {
				try {
					writer.close() ;
				} catch (IOException e2) {
					System.out.println("用户注册释放资源失败！");
				}
			}
		}
	}

}
